from rest_framework.views import APIView
from business.service import *
from config.config import SysConfig
from django.http import HttpResponse

from utils.utils import R

class LoginAPIView(APIView):
    
    def get(self,request):
        
        token_str = request.GET.get("token_str",None)
        if token_str == None :
            return R.param_error(["token_str"])
            
        params = {
            "publicKey":SysConfig.ZERO_PUBLIC_KEY,
            "tokenStr":token_str,
            "appId":SysConfig.ZERO_SYS_APPID
        }
        
        res,msg = LoginService().verify_token(params=params)
        if res:
            request.session["public_key"] = msg 
            return R().dict_result({"public_key":msg})
        
        return R().warning(msg)
    
    def post(self,request):
        public_key = request.session.get("public_key",None)

        if not public_key:
            return R.on_login()
        
        return R().dict_result({"public_key":public_key})
    
    def delete(self,request):
        del request.session["public_key"]

        return R.ok()
        

"""证件照背景替换
"""
class PhotoImageBackgroundAPIView(APIView):
    
    def post(self,request):
        
        photo_file = request.FILES.get("photo_file",None)
        if not photo_file:
            return R.param_error(["photo_file"])
        new_bgc = request.data.get("new_bgc","0,0,255")
        image_type = request.data.get("image_type","com")# 生成图片类型 详细见AI的调用接口 com（替换背景的图） 或者 pha(扣出来的黑白图) 两个 值
        photo_w = request.data.get("photo_w",10)#图片尺寸 
        photo_h = request.data.get("photo_h",10)#图片尺寸 
        public_key = request.session.get("public_key")
        
        new_bgc = new_bgc.split(",")
        new_bgc = (int(new_bgc[0]),int(new_bgc[1]),int(new_bgc[2]))
        
        params = {
            "new_bgc":new_bgc,
            "image_type":image_type,
            "photo_w":photo_w,
            "photo_h":photo_h
        }
        
        metadata = {
            "params":params,
            "public_key":public_key,
            "fcname":"photo_change_background_color"
        }
        
        file_io = PhotoBackgroundChangeService().photo_bgc_change(photo_file=photo_file,metadata=metadata)

        if AiConfig.ENABLE_LOCAL_PHOTO_AI:
            response = HttpResponse(file_io)
            response['Content-Type'] = 'image/png'
            return response
        return R.ok()
